 //
//  CBCReadModel.m
//  CBCReader
//
//  Created by Labanotation on 16/5/31.
//  Copyright © 2016年 okwei. All rights reserved.
//

#import "CBCReadModel.h"
#import "CBCReadConfig.h"
#import "CBCChapterModel.h"
#import "Chapter.h"
#import "BookInfo.h"
#import "CBCReadUtilites.h"
#import "CBCMarkModel.h"
#import "CBCNoteModel.h"
#import "CBCChapterModel.h"
#import "CBCRecordModel.h"
@implementation CBCReadModel

-(instancetype)initWithBookInfo:(BookInfo *)bookInfo andChapters:(NSArray *)chapters{
    self = [super init];
    if (self) {

        self.bookInfo = bookInfo;
        NSMutableArray *mutableChapters = [NSMutableArray array];
        for (Chapter *chapter in chapters){
            CBCChapterModel *character = [[CBCChapterModel alloc]init];
            character.ID = chapter.ID;
            character.title = chapter.name;
            character.num = chapter.num;
            [mutableChapters addObject:character];
        }
        self.chapters = mutableChapters;
        self.font = [NSNumber numberWithFloat:[CBCReadConfig shareInstance].fontSize];
        NSData *modelData = [[NSUserDefaults standardUserDefaults] objectForKey:self.bookInfo.ID];
        if(modelData != nil){
            NSMutableData *data=[[NSMutableData alloc]init];
            NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
            CBCReadModel *model = [unarchive decodeObjectForKey:self.bookInfo.ID];
            self.record = [model.record mutableCopy];
        }
        if(_record == nil){
            _record = [[CBCRecordModel alloc] init];
            _record.chapterModel = _chapters.firstObject;
            _record.chapterCount = _chapters.count;
        }

    }
    return self;
}
-(instancetype)initWithContent:(NSString *)content
{
    self = [super init];
    if (self) {
        NSMutableArray *charpter = [NSMutableArray array];
        [CBCReadUtilites separateChapter:&charpter content:content];
        _chapters = charpter;
        _record = [[CBCRecordModel alloc] init];
        _record.chapterModel = charpter.firstObject;
        _record.chapterCount = _chapters.count;
        _font = [NSNumber numberWithFloat:[CBCReadConfig shareInstance].fontSize];
    }
    return self;
}
-(instancetype)initWithePub:(NSString *)ePubPath;
{
    self = [super init];
    if (self) {
//        _chapters = [CBCReadUtilites ePubFileHandle:ePubPath];;
//        _record = [[CBCRecordModel alloc] init];
//        _record.chapterModel = _chapters.firstObject;
//        _record.chapterCount = _chapters.count;

        _font = [NSNumber numberWithFloat:[CBCReadConfig shareInstance].fontSize];
    }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.chapters forKey:@"chapters"];
    [aCoder encodeObject:self.record forKey:@"record"];
    [aCoder encodeObject:self.font forKey:@"font"];
    [aCoder encodeObject:self.bookInfo forKey:@"bookInfo"];

}
-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.chapters = [aDecoder decodeObjectForKey:@"chapters"];
        self.record = [aDecoder decodeObjectForKey:@"record"];
        self.font = [aDecoder decodeObjectForKey:@"font"];
        self.bookInfo = [aDecoder decodeObjectForKey:@"bookInfo"];
    }
    return self;
}
+(void)updateLocalModel:(CBCReadModel *)readModel key:(NSString *)key
{
    NSMutableData *data=[[NSMutableData alloc]init];
    NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:readModel forKey:key];
    [archiver finishEncoding];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
}
+(id)getLocalModelWithURL:(NSURL *)url
{
    NSString *key = [url.path lastPathComponent];
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (!data) {
        if ([[key pathExtension] isEqualToString:@"txt"]) {
            CBCReadModel *model = [[CBCReadModel alloc] initWithContent:[CBCReadUtilites encodeWithURL:url]];
            [CBCReadModel updateLocalModel:model key:[url lastPathComponent]];
            return model;
        }
        else if ([[key pathExtension] isEqualToString:@"epub"]){
            NSLog(@"this is epub");
            CBCReadModel *model = [[CBCReadModel alloc] initWithePub:url.path];
            [CBCReadModel updateLocalModel:model key:key];
            return model;
        }
        else{
            @throw [NSException exceptionWithName:@"FileException" reason:@"文件格式错误" userInfo:nil];
        }
        
    }
    NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    CBCReadModel *model = [unarchive decodeObjectForKey:key];
    
    if ([model.font floatValue] != [CBCReadConfig shareInstance].fontSize) {
        if ([[key pathExtension] isEqualToString:@"txt"]) {
            CBCReadModel *model = [[CBCReadModel alloc] initWithContent:[CBCReadUtilites encodeWithURL:url]];
            [CBCReadModel updateLocalModel:model key:[url lastPathComponent]];
            return model;
        }
    }
    
    return model;
}
- (NSUInteger)getPageIndexByOffset:(NSUInteger)offset Chapter:(NSUInteger)chapterIndex {
    CBCChapterModel *chapterModel = _chapters[chapterIndex];
    NSArray *pageArray = chapterModel.pageArray;
    
    for (int i = 0; i < pageArray.count - 1; i++) {
        if (offset >= [pageArray[i] integerValue] && offset < [pageArray[i + 1] integerValue]) {
            return i;
        }
    }
    
    if (offset >= [pageArray[pageArray.count - 1] integerValue]) {
        return pageArray.count - 1;
    } else {
        return 0;
    }
}
@end
